package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(value = "/downimg")
public class DownServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        String path = "uploadfiles/" + filename;

        //设置响应的头信息和响应的类型
        resp.setContentType("application/octet-stream");
        //添加响应头
        filename= URLEncoder.encode(filename,"utf-8");
        resp.addHeader("Content-Disposition","attachment;filename=" + filename); //如果文件名为中文，有可能会导致乱码
//        resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));

        //跳转页面
        req.getRequestDispatcher(path).forward(req, resp);
        //清空缓存区
        resp.flushBuffer();

    }
}
